package com.meng.menggaga.ui;

import me.imid.swipebacklayout.lib.SwipeBackLayout;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.meng.menggaga.R;
import com.meng.menggaga.adapter.NaviSpinnerAdapter;
import com.meng.menggaga.application.MainApplication;
import com.meng.menggaga.entity.CommunityCategoryInfos;
import com.meng.menggaga.util.NavigationItems;
import com.meng.menggaga.util.NavigationItems.NAVIGATION_TYPE;
import com.meng.menggaga.util.NavigationItems.NavigationItem;


/**
 * 主页
 * 
 * @author simba
 * 
 */
public class MainActivity extends BaseActivity implements
        NavigationDrawerFragment.NavigationDrawerCallbacks, OnNavigationListener {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

    private final long SPACETIME = 2000;
    private long mLastBackTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.activity_main);

        mNavigationDrawerFragment =
                (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(
                        R.id.navigation_drawer);
        // mTitle = getTitle();

        onSectionAttached(NavigationItems.sNavigationTypes[0]);

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        // set home as up button enable
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        loadCommunityCategory();

        setEdgeTrackingEnable(SwipeBackLayout.EDGE_RIGHT);

    }

    CommunityCategoryInfos mCommunityCategoryInfos;

    private void loadCommunityCategory() {
        MainApplication.get().getMoccaApi()
                .getCommunityCategory("36", new Listener<CommunityCategoryInfos>() {

                    @Override
                    public void onResponse(CommunityCategoryInfos response) {
                        mCommunityCategoryInfos = response;
                        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                        getSupportActionBar().setListNavigationCallbacks(
                                new NaviSpinnerAdapter(getBaseContext(), response.array,
                                        R.layout.list_item_community_category), MainActivity.this);
                        getSupportActionBar().setDisplayShowTitleEnabled(false);
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
    }

    @Override
    public void onNavigationDrawerItemSelected(NavigationItem type) {

        if (type.type == NAVIGATION_TYPE.COMMUNITY) {
            handleDrawer(false);
            // update the main content by replacing fragments
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, CommunityListFragment.newInstance(1)).commit();
        } else if (type.type == NAVIGATION_TYPE.ACTIVITY) {
            handleDrawer(false);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.container, new ActivitiesFragment())
                    .commit();
        } else if (type.type == NAVIGATION_TYPE.SUBJECT) {
            handleDrawer(false);
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.container, new SubjectFragment())
                    .commit();
        } else if (type.type == NAVIGATION_TYPE.RANKING) {
            handleDrawer(true);
            startActivity(new Intent(this, RankingActivity.class));
            overridePendingTransition();
        } else if (type.type == NAVIGATION_TYPE.SETTING) {
            handleDrawer(true);
            MainApplication.mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    startActivity(new Intent(getBaseContext(), SettingActivity.class));
                    overridePendingTransition();
                }
            }, 150);
        }
        onSectionAttached(type);
    }

    private void handleDrawer(boolean delay) {
        if (null != mNavigationDrawerFragment) {
            mNavigationDrawerFragment.closeDrawer(delay);
        }
    }

    public void onSectionAttached(NavigationItem item) {
        if (item.type == NAVIGATION_TYPE.COMMUNITY || item.type == NAVIGATION_TYPE.SUBJECT
                || item.type == NAVIGATION_TYPE.ACTIVITY) {
            mTitle = getString(item.nameRes);
        }
    }

    public void restoreActionBar() {
        if (!TextUtils.isEmpty(mTitle)) {
            ActionBar actionBar = getSupportActionBar();
            actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setTitle(mTitle);
        } else {
            getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            getSupportActionBar().setListNavigationCallbacks(
                    new NaviSpinnerAdapter(getBaseContext(), mCommunityCategoryInfos.array,
                            R.layout.list_item_community_category), MainActivity.this);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            setEdgeTrackingEnable(SwipeBackLayout.EDGE_RIGHT);
            return true;
        } else {
            setEdgeTrackingEnable(0);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            startActivity(new Intent(this, SettingActivity.class));
            overridePendingTransition();
            return true;
        } else if (id == R.id.action_exit) {
            System.exit(0);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(int arg0, long arg1) {
        // FragmentManager fragmentManager = getSupportFragmentManager();
        // fragmentManager
        // .beginTransaction()
        // .replace(R.id.container,
        // CommunityListFragment.newInstance(mCommunityCategoryInfos.get(arg0).fid))
        // .commit();
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mNavigationDrawerFragment.isDrawerOpen()) {
                mNavigationDrawerFragment.closeDrawer(false);
                return true;
            } else {
                if (System.currentTimeMillis() - mLastBackTime > SPACETIME) {
                    showStandardToast(R.string.again_click_to_back);
                    mLastBackTime = System.currentTimeMillis();
                    return true;
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected int layoutResId() {
        // TODO Auto-generated method stub
        return R.layout.activity_main;
    }

}
